Grokking Tree Coding Patterns for Interviews
Rate this course
Ask Author
Contribute
Back to course home

0% completed

Vote For New Content
Course Overview
Introduction to Tree
Types of Tree
BST Traversal Techniques
BST Operations
Introduction to Level Order Traversal Pattern
Reverse Level Order Traversal (easy)
Solution: Reverse Level Order Traversal
Find Largest Value in Each Tree Row (medium)
Solution: Find Largest Value in Each Tree Row
Maximum Width of Binary Tree (medium)
Solution: Maximum Width of Binary Tree
Maximum Level Sum of a Binary Tree (medium)
Solution: Maximum Level Sum of a Binary Tree
Zigzag Traversal (medium)
Solution: Zigzag Traversal
Even Odd Tree (medium)
Solution: Even Odd Tree
N-ary Tree Level Order Traversal (hard)
Solution: N-ary Tree Level Order Traversal
Introduction to Tree Depth Pattern
Maximum Depth (or Height) of Binary Tree (easy)
Solution: Maximum Depth (or Height) of Binary Tree
Minimum Depth of a Binary Tree (easy)
Solution: Minimum Depth of a Binary Tree
Balanced Binary Tree (easy)
Solution: Balanced Binary Tree
Tree Diameter (easy)
Solution: Tree Diameter
Maximum Depth of N-ary Tree (easy)
Solution: Maximum Depth of N-ary Tree
Find maximum depth of subtree (medium)
Solution: Find maximum depth of subtree
Introduction to Root to Leaf Path Pattern
Binary Tree Paths (easy)
Solution: Binary Tree Paths
Sum of Root To Leaf Binary Numbers (easy)
Solution: Sum of Root To Leaf Binary Numbers
Insufficient Nodes in Root to Leaf Paths (medium)
Solution: Insufficient Nodes in Root to Leaf Paths
Smallest String Starting From Leaf (medium)
Solution: Smallest String Starting From Leaf
Pseudo-Palindromic Paths in a Binary Tree (medium)
Solution: Pseudo-Palindromic Paths in a Binary Tree
All Paths for a Sum (medium)
Solution: All Paths for a Sum
Sum of Path Numbers (medium)
Solution: Sum of Path Numbers
Path With Given Sequence (medium)
Solution: Path With Given Sequence
Count Paths for a Sum (medium)
Solution: Count Paths for a Sum
Introduction to Leaf Processing Pattern
Sum of Left Leaves (easy)
Solution: Sum of Left Leaves
Leaf-Similar Trees (easy)
Solution: Leaf-Similar Trees
Check if all leaves are at same level (medium)
Solution: Check if all leaves are at same level
Delete Leaves With a Given Value (medium)
Solution: Delete Leaves With a Given Value
Deepest Leaves Sum (medium)
Solution: Deepest Leaves Sum
Introduction to Tree View Pattern
Right View of a Binary Tree (medium)
Solution: Right View of a Binary Tree
Top View Of the Binary Tree (medium)
Solution: Top View Of the Binary Tree
Bottom View Of the Binary Tree (medium)
Solution: Bottom View Of the Binary Tree
Boundary of Binary Tree (medium)
Solution: Boundary of Binary Tree
Introduction to Comparison of Two Trees Pattern
Symmetric Tree (easy)
Solution: Symmetric Tree
Mirror Image Trees (medium)
Solution: Mirror Image Trees
Subtree of Another Tree (easy)
Solution: Subtree of Another Tree
Isomorphic Trees (medium)
Solution: Isomorphic Trees
Introduction to Serialize and Deserialize Tree Pattern
Serialize and Deserialize BST (medium)
Solution: Serialize and Deserialize BST
Verify Preorder Serialization of a Binary Tree (medium)
Solution: Verify Preorder Serialization of a Binary Tree
Create Binary Tree From Descriptions (medium)
Solution: Create Binary Tree From Descriptions
Serialize and Deserialize N-ary Tree (hard)
Solution: Serialize and Deserialize N-ary Tree
Solution: Path Sum III

Problem Statement

Given the root of a binary tree and an integer targetSum, return the count of number of paths in the tree where the sum of the values along the path equals targetSum.

A path can start and end at any node, but it must go downward, meaning it can only travel from parent nodes to child nodes.`

Examples

Example 1:

  • Input: targetSum = 10, root = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
      1
     / \
    2   3
   / \ / \
  4  5 6  7
 / \ /
8  9 10
  • Expected Output: 3
  • Justification: The paths that sum to 10 are:
    • 1 → 3 → 6
    • 3 → 7
    • 10

Example 2:

  • Input: targetSum = 12, root = [5, 4, 6, 3, null, 7, 8, null, null, 2, 1]
    5
   / \
  4   6
 /   / \
3   7   8
   / \      
   2  1

  • Expected Output: 1
  • Justification: The paths that sum to 12 are:
    • 5 → 4 → 3

Example 3:

  • Input: targetSum = 18, root = [10, 5, -3, 3, 2, null, 11, null, null, 1]
   10
   / \
  5  -3
 / \   \
3   2   11
   / 
  1 

  • Expected Output: 3
  • Justification: The path that sums to 18 is:
    • 10 → 5 → 3
    • 10 → -3 → 11
    • 10 → 5 → 2 → 1

Constraints:

  • The number of nodes in the tree is in the range [0, 1000].
  • -109 <= Node.val <= 109
  • -1000 <= targetSum <= 1000

Solution

To solve this problem, we need to explore all possible paths in the tree and check if any of them sum up to targetSum. We can use a depth-first search (DFS) approach to traverse the tree. During the traversal, we'll maintain a current path and calculate the running sum of the nodes in this path. To efficiently find the number of paths that sum to the target, we can use a hash map to store the cumulative sums we encounter and their frequencies. This way, for any node, we can determine if there is a sub-path (ending at the current node) whose sum equals targetSum by checking if (currentSum - targetSum) exists in the hash map.

This approach ensures we efficiently count all valid paths without having to repeatedly traverse the same nodes, making it more effective than a brute-force solution. The use of a hash map helps us keep track of the cumulative sums and their frequencies, allowing quick lookups and updates.

Step-by-step Algorithm

  1. Initialization:

    • Create a hash map prefixSumCount to store the cumulative sums and their frequencies. Initialize it with {0: 1} to handle the base case where a path itself equals targetSum.
  2. Define DFS Function and Add Base Case:

    • Create a helper function dfs(node, currSum, targetSum, prefixSumCount).
    • If the current node is null, return 0 as there are no paths through this node.
  3. Update Current Sum:

    • Add the value of the current node to currSum.
  4. Calculate Paths:

    • Check if (currSum - targetSum) exists in prefixSumCount. This gives the number of valid paths that end at the current node.
    • Retrieve the count from the hash map and store it in numPathsToCurr.
  5. Update Prefix Sum:

    • Update prefixSumCount with the current sum. Increment its count by 1.
  6. DFS Recursion:

    • Recursively call dfs on the left child.
    • Recursively call dfs on the right child.
    • Sum the results of the recursive calls with numPathsToCurr.
  7. Go Back to the Parent Node:

    • After processing both children, decrement the count of currSum in prefixSumCount by 1 to go back to the parent node.
  8. Return Result:

    • Return the total number of paths found.

Algorithm Walkthrough

Input:

  • root = [10, 5, -3, 3, 2, null, 11, null, null, 1]
  • targetSum = 18
  1. Initialization:

    • prefixSumCount = {0: 1}
    • Start DFS with the root node (10).
  2. At Node 10:

    • currSum = 0 + 10 = 10
    • numPathsToCurr = prefixSumCount.get(10 - 18, 0) = 0
    • prefixSumCount = {0: 1, 10: 1}
    • Recur to left child (5).
  3. At Node 5:

    • currSum = 10 + 5 = 15
    • numPathsToCurr = prefixSumCount.get(15 - 18, 0) = 0
    • prefixSumCount = {0: 1, 10: 1, 15: 1}
    • Recur to left child (3).
  4. At Node 3:

    • currSum = 15 + 3 = 18
    • numPathsToCurr = prefixSumCount.get(18 - 18, 0) = 1
    • prefixSumCount = {0: 1, 10: 1, 15: 1, 18: 1}
    • Total paths that end at node 3: 1.
  5. At Node 5 (continued):

    • Recur to right child (2).
  6. At Node 2:

    • currSum = 15 + 2 = 17
    • numPathsToCurr = prefixSumCount.get(17 - 18, 0) = 0
    • prefixSumCount = {0: 1, 10: 1, 15: 1, 17: 1}
    • Recur to left child (null).
      • Return 0.
  7. At Node 2 (continued):

    • Recur to right child (1).
  8. At Node 1:

    • currSum = 17 + 1 = 18
    • numPathsToCurr = prefixSumCount.get(18 - 18, 0) = 1
    • prefixSumCount = {0: 1, 10: 1, 15: 1, 17: 1, 18: 1}
    • Total paths that end at node 1: 1.
  9. At Node 2 (continued):

    • prefixSumCount = {0: 1, 10: 1, 15: 1, 17: 0}
    • Backtrack to node 5.
    • Total paths from node 2: 1.
  10. At Node 5 (continued):

    • prefixSumCount = {0: 1, 10: 1, 15: 0}
    • Backtrack to node 10.
    • Total paths from node 5: 2.
  11. At Node 10 (continued):

    • Recur to right child (-3).
  12. At Node -3:

    • currSum = 10 - 3 = 7
    • numPathsToCurr = prefixSumCount.get(7 - 18, 0) = 0
    • prefixSumCount = {0: 1, 10: 1, 7: 1}
    • Recur to left child (null).
      • Return 0.
  13. At Node -3 (continued):

    • Recur to the right child (11).
  14. At Node 11:

    • currSum = 7 + 11 = 18
    • numPathsToCurr = prefixSumCount.get(18 - 18, 0) = 1
    • prefixSumCount = {0: 1, 10: 1, 7: 1, 18: 1}
    • Recur to left child (null).
      • Return 0.
  15. At Node 11 (continued):

    • Recur to right child (null).
      • Return 0.
    • prefixSumCount = {0: 1, 10: 1, 7: 1, 18: 0}
    • Backtrack to node -3.
    • Total paths that end at node 11: 1.
  16. At Node -3 (continued):

    • prefixSumCount = {0: 1, 10: 1, 7: 0}
    • Backtrack to node 10.
    • Total paths from node -3: 1.
  17. At Node 10 (continued):

    • prefixSumCount = {0: 1, 10: 0}
    • Total paths from node 10: 3.

Total Paths: 3 (10→5→3, 10→5→2→1, 10→-3→11)

Code

Java
Saved to Cloud

. . . .

Complexity Analysis

Time Complexity

The time complexity of the algorithm is , where (N) is the number of nodes in the binary tree. This is because each node is visited exactly once in the depth-first search traversal.

Space Complexity

The space complexity is also due to the space required for the hash map (prefixSumCount) and the recursion stack in the worst case when the binary tree is completely unbalanced.

Path Sum III (medium)
Validate Binary Search Tree (medium)
Mark as Completed

On this page

Problem Statement

Examples

Solution

Step-by-step Algorithm

Algorithm Walkthrough

Code

Complexity Analysis

Time Complexity

Space Complexity